#include "renderwindow.h"

#include "enums.h"
#include "context.h"
#include "system/window.h"

namespace dw {
	namespace graffiti {

/*static*/ const uint RenderWindow::DefaultClearMode = clear::color | clear::depth;
/*static*/ const Colorf RenderWindow::DefaultClearColor = Colorf::Orange;
/*static*/ const float32 RenderWindow::DefaultClearDepth = 1.0f;
/*static*/ const int32 RenderWindow::DefaultClearStencil = 0;

void RenderWindow::clear()
{
	dwAssert(m_context != NULL, "Invalid internal state");
	dwAssert(m_context->isValid(), "Invalid context");

	glViewport(0, 0, m_window->getWidth(), m_window->getHeight());

	if (m_clearMode != clear::none)
	{
		GLbitfield clearFlags = 0;

		if ((m_clearMode & clear::color) != 0)
		{
			clearFlags |= GL_COLOR_BUFFER_BIT;

			glClearColor(m_clearColor.r, m_clearColor.g, m_clearColor.b, m_clearColor.a);
		}
		if ((m_clearMode & clear::depth) != 0)
		{
			clearFlags |= GL_DEPTH_BUFFER_BIT;

			glClearDepth(m_clearDepth);
		}
		if ((m_clearMode & clear::stencil) != 0)
		{
			clearFlags |= GL_STENCIL_BUFFER_BIT;

			glClearStencil(m_clearStencil);
		}

		glClear(clearFlags);
	}
}

void RenderWindow::present()
{
	dwAssert(m_context != NULL, "Invalid internal state");
	dwAssert(m_context->isValid(), "Invalid context");

	if (::SwapBuffers(m_context->getDeviceContext()) == FALSE)
	{
		dwFail("todo handle this error");
	}
}

dw::uint32 RenderWindow::getWidth() const
{
	return m_window->getWidth();
}

dw::uint32 RenderWindow::getHeight() const
{
	return m_window->getHeight();
}

RenderWindow::RenderWindow(dw::system::Window* window, Context* context)
:	m_context(context)
,	m_window(window)
,	m_clearMode(DefaultClearMode)
,	m_clearColor(DefaultClearColor)
,	m_clearDepth(DefaultClearDepth)
,	m_clearStencil(DefaultClearStencil)
{
}

	} // namespace graffiti
} // namespace dw
